<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/02/18
 * Time: 10:29
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\wms;

use app\admin\controller\BaseController;
use app\common\model\Warehouse;
use app\common\model\WarehouseArea;
use app\common\model\WarehouseLocation;
use app\common\model\WarehouseShelf;
use app\common\service\product\WarehouseService;

/**
 * 库位管理
 * Class WlocationController
 * @package app\admin\controller\wms
 */
class WlocationController extends BaseController
{
    /**
     * 库位列表
     * @date 2021/02/18
     * @author longli
     */
    public function index()
    {
        if($this->request->isAjax())
        {
            $location = WarehouseLocation::with(['warehouse', 'shelf.area'])
                ->where('warehouse_id', $this->warehouse->warehouse_id)
                ->order('warehouse_id, location_id desc');
            $this->searchModel($location, [
                'eq' => ['shelf_id', 'code', 'status', 'is_used'],
                'times' => ['create_time']
            ]);
            $swhere = [];
            if($area = $this->request->post('area_id')) $swhere[] = ['area_id', '=', $area];
            if($scode = $this->request->post('scode')) $swhere[] = ['code', '=', trim($scode)];
            if(!empty($swhere))
            {
                $location->wherein('shelf_id', function($query)use($swhere)
                {
                    $query->table(WarehouseShelf::getTable())->where($swhere)->field('shelf_id');
                });
            }
            $limit = $this->getPageSize();
            $location = $location->paginate($limit);
            $this->assign("list", $location->getCollection());
            $this->assign("page", $location->render());
            return $this->fetch('lists');
        }
        $this->assign('area', WarehouseArea::getArea($this->warehouse->warehouse_id));
        $this->assign("status", ["禁用", "可用"]);
        $this->assign("used", ["否", "是"]);
        return $this->fetch('index');
    }

    /**
     * 添加库位
     * @date 2021/02/18
     * @author longli
     */
    public function add()
    {
        if(($id = $this->request->get('location_id')) && ($location = WarehouseLocation::get($id)))
        {
            $this->assign('location', $location);
            $this->assign('shelf', WarehouseShelf::getShelf($location->warehouse_id, $location->shelf->area_id));
        }
        $this->assign('area', WarehouseArea::getArea($this->warehouse->warehouse_id));
        return $this->fetch('add');
    }

    /**
     * 保存库位
     * @date 2021/02/18
     * @author longli
     */
    public function save()
    {
        $data = [
            'status' => $this->request->request('status', WarehouseLocation::IS_NO),
            'warehouse_id' => $this->warehouse->warehouse_id,
        ];
        if($this->request->isPost())
        {
            $this->validateSave();
            // 限制更新字段
            $data += $this->request->only(['status', 'max_qty', 'remark', 'floor', 'location_id'], 'post');
            if(empty($data['code'])) $data = ['code' => WarehouseLocation::generateCode()] + $data;
        }
        else
        {
            $locationId = $this->request->get('location_id');
            if(empty($locationId)) $this->error('非法请求');
            $data += ['location_id' => $locationId];
        }
        WarehouseService::getInstance()->addLocation($data)
            ? $this->success('操作成功')
            : $this->error('操作失败');
    }

    /**
     * 验证保存库位
     * @date 2021/02/18
     * @author longli
     */
    private function validateSave()
    {
        $validate = \think\facade\Validate::make([
            'shelf_id'  => 'require',
            'floor'  => 'egt:0',
            'max_qty'  => 'egt:0',
        ],[
            'shelf_id.require' => '货架必选',
            'floor.egt' => '货架层级不能小于0',
            'max_qty.egt' => '库位最大数量不能小于0',
        ]);
        $data = $this->request->post();
        if(!$validate->batch()->check($data)) $this->error(join(', ', $validate->getError()));
        if(!isset($data['location_id']) && !empty($data['code']) && WarehouseLocation::hasCode($data['code'], $this->warehouse->warehouse_id))
            $this->error('库位已存在');
    }
}